package com.example.rbac.uitls;

import com.example.rbac.entity.Menu;
import com.google.common.collect.Lists;

import java.util.List;

/**
 * Created by Administrator on 2017/10/17.
 */
public class CollectionUtils {

    private static volatile CollectionUtils collectionUtils = null;

    private CollectionUtils() {
    }

    public static CollectionUtils getInstance(){
        if (collectionUtils == null){
            synchronized (CollectionUtils.class){
                if (collectionUtils == null){
                    collectionUtils = new CollectionUtils();
                }
            }
        }
        return collectionUtils;
    }

    /**
     *根据id获取所有父级目录 组合一维数组
     * @param list
     * @param pid
     * @return
     */
    public static List<Menu> getParents(List<Menu> list, String pid){
        List<Menu> arr = Lists.newLinkedList();
        for (Menu menu : list) {
            if(pid.equals(menu.getId())){
                arr.addAll(getParents(list, menu.getPid()));
                arr.add(menu);  break;
            }
        }
        return arr;
    }


    /**
     * 组合多维数组
     * @param menus
     * @param root
     * @return
     */

    public static List<Menu> ListMenu(List<Menu> menus, String root){
        List<Menu> arr = Lists.newLinkedList();
        for (Menu m : menus) {
            if (m.getPid().equals(root)){
                m.setList(ListMenu(menus, m.getId()));
                arr.add(m);
            }
        }
        return arr;
    }

    /**
     *
     */
    public static List<Menu> pushOneGroup(List<Menu> list, String pid){
        List<Menu> arr = Lists.newLinkedList();
        for(Menu m : list){
            if(pid.equals(m.getPid())){
                arr.add(m);
                arr.addAll(pushOneGroup(list, m.getId()));
            }
        }
        return arr;
    }

}
